package com.qhit.test;

import org.junit.jupiter.api.Test;

import java.sql.*;

/**
 * 需求：编写测试类ResultSetMetaDataTest1，通过sno查询Student表中某个学生的信息，然后输出结果集中所有字段的名称和字段的类型。
 *
 * @author 村头老杨头
 * @version 1.0
 * @date 2021/9/27 16:31
 */
public class ResultSetMetaDataTest1 {
    private String driver = "com.mysql.cj.jdbc.Driver";
    private String url = "jdbc:mysql://127.0.0.1:3306/edu";
    private String username = "root";
    private String password = "123456";
    @Test
    public void testResultSetMetaData() throws ClassNotFoundException, SQLException {
        //ResultSetMetaData 表的元数据类
        String sno = "101";
        //加载驱动
        Class.forName(driver);
        //创建连接
        Connection conn = DriverManager.getConnection(url, username, password);
        //SQL预处理
        String sql = "select * from student where sno=?";
        PreparedStatement ps = conn.prepareStatement(sql);
        //填充问号
        ps.setObject(1,sno);
        //发送SQL并返回结果集 rs
        ResultSet rs = ps.executeQuery();
        //表元数据对象
        ResultSetMetaData rsmd = rs.getMetaData();
        for (int i = 1; i <= rsmd.getColumnCount(); i++) {
            System.out.println("第"+i+"个字段:"+ rsmd.getColumnName(i)+"\t字段类型："+rsmd.getColumnTypeName(i));
        }
        //关闭
        rs.close();
        ps.close();
        conn.close();
    }
}
